<template>
  <div class="panel">
    <el-dialog :title="action==='add'?'添加轮播图片':'修改轮播图片'" :visible.sync="visible" width="330px" @opened="opened" :close-on-click-modal="false">
      <el-form :model="form" :rules="rules" ref="form" label-width="80px">
        <el-form-item label="图片标题"  prop="title">
          <el-input v-model.trim="form.title" ref="title"></el-input>
        </el-form-item>
        <el-form-item label="上传图片" prop="picture">
          <el-upload
            class="mypicture"
            action="http://cloud.scnew.com.cn/api/user/upload"
            :show-file-list="false"
            :on-success="uploadSuccess"
            :before-upload="beforeUpload">
            <img v-if="form.picture" :src="form.picture">
            <i v-else class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="图片链接">
          <el-input v-model.trim="form.picurl"></el-input>
        </el-form-item>
        <el-form-item label="排序" prop="orderid">
          <el-input-number v-model="form.orderid" :min="1" :max="10"></el-input-number>
        </el-form-item>
        <el-form-item label="审核" >
          <el-switch v-model="form.state" active-color="#13ce66" :active-value="2" :inactive-value="1"></el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>

    <div class="heading">
      <h1>轮播列表</h1>
      <el-breadcrumb separator="/">
        <el-breadcrumb-item to="/app">首页</el-breadcrumb-item>
        <el-breadcrumb-item to="/app/carousel">轮播管理</el-breadcrumb-item>
        <el-breadcrumb-item>轮播列表</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <div class="search">
      <div class="condition">
        <el-button v-if="ids.length" type="danger" size="small" @click="del(ids)">批量删除</el-button>
        <el-select v-model="condition.state" placeholder="是否审核" size="small" class="state" clearable>
          <el-option :value="2" label="审核"></el-option>
          <el-option :value="1" label="未审核"></el-option>
         </el-select>
        <el-input v-model="condition.keyword" placeholder="请输入轮播图标题/链接" size="small" clearable class="keyword" ></el-input>
      </div>
      <el-button type="success" size="small" @click="add">新增</el-button>
    </div>
    <el-table
      v-loading="loading"
      :data="pageData"
      tooltip-effect="dark"
      style="width: 100%"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" prop="id"></el-table-column>
      <el-table-column label="排序" width="100" prop="orderid"></el-table-column>
      <el-table-column label="缩略图" width="150">
        <template v-slot="scope">
          <img :src="scope.row.picture" height='40'>
        </template>
      </el-table-column>
      <el-table-column prop="title" label="标题" width="200"></el-table-column>
      <el-table-column prop="picurl" label="链接" width="200"></el-table-column>
      <el-table-column label="审核">
        <template v-slot="scope">
          <el-switch v-model="scope.row.state" active-color="#13ce66" :active-value="2"
          :inactive-value="1" @change="stateChange($event,scope.row.id)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column  label="操作" width="160">
        <template v-slot="scope">
          <el-button size="mini" plain @click="updata(scope.row)">修改</el-button>
          <el-button size="mini" type="danger" @click="del([scope.row.id])">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination background layout="total, prev, pager, next"
    :page-size="condition.pageSize" :total="searchData.length" :current-page.sync="condition.page"
     class="mypage">
    </el-pagination>
  </div>
</template>

<script>
export default {
  data () {
    return {
      action: null,
      visible: false,
      form: {},
      loading: true,
      condition: { page: 1, pageSize: 3 },
      tableData: [],
      ids: [],
      rules: {
        title: [
          { required: true, message: '请输入分类名称' }
        ],
        picture: [
          { required: true, message: '请上传图片' }
        ],
        orderid: [
          { required: true, message: '请输入排序' }
        ]
      }
    }
  },
  computed: {
    searchData () {
      const { state, keyword } = this.condition
      return this.tableData.filter(item => {
        return (item.state === +state || !state) && (item.title.includes(keyword) || item.picurl.includes(keyword) || !keyword)
      }).sort((a, b) => a.orderid - b.orderid)
    },
    pageData () {
      const { page, pageSize } = this.condition
      const start = (page - 1) * pageSize
      const end = start + pageSize
      return this.searchData.slice(start, end)
    }
  },
  watch: {
    'condition.state' () {
      this.condition.page = 1
    },
    'condition.keyword' () {
      this.condition.page = 1
    }
  },
  created () {
    this.query()
  },
  methods: {
    opened () {
      this.$refs.title.focus()
    },
    // 保存
    save () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 添加保存时
          if (this.action === 'add') {
            this.$http.post('carousel/add', { ...this.form }).then(res => {
              if (res.err > 0) {
                this.$message.error(res.desc)
              } else {
                this.$message.success(res.desc)
                if (this.condition.page === 1) {
                  this.query()
                } else {
                  this.condition.page = 1
                }
                this.visible = false
              }
            })
          } else if ((this.action === 'updata')) { // 修改保存时
            this.$http.post('carousel/updata', { ...this.form }).then(res => {
              if (res.err > 0) {
                this.$message.error(res.desc)
              } else {
                this.$message.success(res.desc)
                this.query()
                this.visible = false
              }
            })
          }
        }
      })
    },

    // 查询刷新
    query () {
      this.$http.get('carousel/list').then(res => {
        if (res.err > 0) {
          this.$message.error(res.desc)
        } else {
          this.tableData = res.result
          setTimeout(() => { this.loading = false }, 500)
        }
      })
    },

    // 添加
    add () {
      this.action = 'add'
      this.visible = true
      this.form = { orderid: 1 }
    },

    // 修改
    updata (row) {
      this.action = 'updata'
      this.visible = true
      this.form = { ...row }
    },

    // 删除
    del (ids) {
      this.$confirm('你确定要删除吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.$http.post('carousel/delete', { ids }).then(res => {
          if (res.err > 0) {
            this.$message.error(res.desc)
          } else {
            this.$message.success(res.desc)
            this.query()
          }
        })
      }).catch(() => {})
    },

    // 审核状态修改
    stateChange (state, id) {
      this.$http.post('carousel/state', { id, state }).then(res => {
        if (res.err > 0) {
          this.$message.error(res.desc)
        } else {
          this.$message.success(res.desc)
        }
      })
    },

    // 全选
    handleSelectionChange (row) {
      this.ids = row.map(item => item.id)
    },

    // 图片上传
    beforeUpload (file) {
      const type = file.type.split('/')[1].toLowerCase()
      const isPic = ['jpeg', 'png', 'gif', 'jpg', 'webp']
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isPic.includes(type)) {
        this.$message.error('上传图片只能是 ' + isPic + ' 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isPic && isLt2M
    },
    uploadSuccess (res) {
      if (res.err > 0) {
        this.$message.error(res.desc)
      } else {
        this.$message.success(res.desc)
        this.$set(this.form, 'picture', res.result)
      }
    }
  }
}
</script>

<style lang="less">
  .mypicture{
    .el-upload {
      border: 1px solid #DCDFE6;
      border-radius: 4px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      &:hover {
        border-color: #0fecec;
      }
      img{
        display: block;
        width: 100px;
        height: 50px;
      }
      [class*="el-icon-"]{
        width: 200px;
        height: 100px;
        line-height: 100px;
        text-align: center;
        font-size: 24px;
        color: #8c939d;
      }
    }
  }
</style>
